<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\DisposeStoreRequest;
use App\Http\Requests\DisposeUpdateRequest;
use App\Models\MedicalDispose;
use App\Project\Filters\DisposeFilter;
use App\Project\Transform;
use App\Transformers\DisposeTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

/**
 * 处理项目控制器
 * Class DisposeController
 * @package App\Http\Controllers\Manage
 */
class DisposeController extends ApiController
{
    /**
     * 处理存储 多次提交视为更新
     * @param \App\Http\Requests\DisposeStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(DisposeStoreRequest $request)
    {
        $input = (new DisposeFilter($request))->input();

        $result = MedicalDispose::updateOrCreate(['record_id' => $input['record_id']], $input);

        return $this->response(['id' => $result['id']]);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MedicalDispose::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {

            $data = MedicalDispose::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失处理ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalDispose::class);
        }

        return $this->item($data, new DisposeTransformer());
    }

    /**
     * @param \App\Http\Requests\DisposeUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(DisposeUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        $input = (new DisposeFilter($request))->except(['id', 'record_id']);

        $input = (new Transform())->setArray($input)->convertArrayToJson(
            ['control_objectives', 'advise', 'inspection_plan', 'schedule', 'medication', 'cn_medication']
        )->get();

        $result = MedicalDispose::where($where)->update($input);

        return $this->responseForUpdate($result);
    }
}
